﻿using Api.Shared.Model;
using Api.Shared.Model.Chengya;
using Api.Shared.Model.Web.Login;
using Api.Shared.MyPlc.S7;
using Api.Shared.Sugar;
using Api.Shared.Utils;
using Api.Shared.Utils.Yanji;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FitterTest.Controllers
{
    [Route("api/private/v1/[controller]/[action]")]
    [ApiController]
    [EnableCors("any")]
    public class WorkorderController : ControllerBase
    {
        private readonly ISugarClientService helper;
        private readonly IS7ConnService s7;
        private readonly MySession mySession;

        public WorkorderController(
            [FromKeyedServices(nameof(SqlName.sqlite))] ISugarClientService helper,
            IS7ConnService s7,
            MySession mySession
        )
        {
            this.helper = helper;
            this.s7 = s7;
            this.mySession = mySession;
        }

        [HttpGet]
        public async Task<ActionResult<MyApiResponse<List<DB91WorkorderSqlite>>>> GetWorkorderHis(
            [FromQuery] QueryInfo queryInfo
        )
        {
            if (queryInfo.Pagenum <= 0)
            {
                return BadRequest(new MyApiResponse<List<DB91WorkorderSqlite>>(false, new()));
            }
            if (queryInfo.Pagesize <= 0)
            {
                return NotFound(new MyApiResponse<List<DB91WorkorderSqlite>>(false, new()));
                ;
            }
            int totalNumber = 0;

            var exp = Expressionable.Create<DB91WorkorderSqlite>();

            exp.AndIF(
                !string.IsNullOrWhiteSpace(queryInfo.Query),
                x => x.WorkOrder.Contains(queryInfo.Query)
            );

            exp.AndIF(queryInfo.DateStart != null, x => x.Time > queryInfo.DateStart);

            exp.AndIF(queryInfo.DateEnd != null, x => x.Time < queryInfo.DateEnd);

            exp.AndIF(
                queryInfo.DateEnd != null && queryInfo.DateStart != null,
                x => (x.Time < queryInfo.DateEnd && x.Time > queryInfo.DateStart)
            );

            //vue 分页仅仅 需要总数量 和 当前页. 而handycontrol 需要 总页数(用总数量算出来) 和当前页. 都不需要sqlsugar的 totalpage 总页数
            RefAsync<int> total = 0;

            var a = await helper
                .Db.Queryable<DB91WorkorderSqlite>()
                .Where(exp.ToExpression())
                .ToPageListAsync(queryInfo.Pagenum, queryInfo.Pagesize, total);

            var aa = new MyApiResponse<List<DB91WorkorderSqlite>>(true, a);
            aa.Total = total;
            aa.Pagenum = queryInfo.Pagenum;
            return aa;
        }

        [HttpPost]
        public async Task<IActionResult> AddWorkOrder([FromBody] DB91WorkorderSqlite workOrder)
        {
            if (workOrder != null)
            {
                int count = await helper.Db.Insertable(workOrder).ExecuteCommandAsync();

                return Ok();
            }

            return StatusCode(204, "Failed");
        }

        /// <summary>
        /// 单个删除
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public IActionResult DeleteUserById(string id)
        {
            int count = this
                .helper.Db.Deleteable<DB91WorkorderSqlite>()
                .In(int.Parse(id))
                .ExecuteCommand();
            if (count > 0)
            {
                return Ok();
            }
            else
            {
                return StatusCode(204, "Failed");
            }
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> SetCommandById(string id)
        {
            try
            {
                var cmd = await this
                    .helper.Db.Queryable<DB91WorkorderSqlite>()
                    .InSingleAsync(int.Parse(id));
                if (cmd == null)
                {
                    return StatusCode(204, "查询目录为空");
                }

                return Ok();
            }
            catch (Exception ex)
            {
                return StatusCode(204, $"Failed{ex.Message}");
            }
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> SetFengtouCommandById(string id)
        {
            try
            {
                DB91WorkorderSqlite fengtou = await this
                    .helper.Db.Queryable<DB91WorkorderSqlite>()
                    .InSingleAsync(int.Parse(id));
                if (fengtou == null)
                {
                    return StatusCode(204, "查询目录为空");
                }

                //var FengtouDto = mapper.Map<ParamFengtouDto>(Fengtou);
                OperationRecord operationRecord =
                    new()
                    {
                        Operator = mySession.MyToken,
                        Time = DateTime.Now,
                        Content = $"DB91WorkorderSqlite id:{id}"
                    };

                var count1 = await this
                    .helper.Db.Insertable<OperationRecord>(operationRecord)
                    .ExecuteCommandAsync();
                ;
                return Ok();
            }
            catch (Exception ex)
            {
                return StatusCode(204, $"Failed{ex.Message}");
            }
        }

        //////////工单反馈
        ///

        [HttpGet]
        public async Task<
            ActionResult<MyApiResponse<List<WorkOrderFeedback>>>
        > GetWorkorderFeedback([FromQuery] QueryInfo queryInfo)
        {
            if (queryInfo.Pagenum <= 0 || queryInfo.Pagesize <= 0)
            {
                return BadRequest(new MyApiResponse<List<WorkOrderFeedback>>(false, new()));
            }
            int totalNumber = 0;
            RefAsync<int> total = 0;
            var exp = Expressionable.Create<WorkOrderFeedback>();

            if (!string.IsNullOrWhiteSpace(queryInfo.Query))
                exp.And(x => x.WorkOderId.Contains(queryInfo.Query));

            if (queryInfo.DateStart != null)
                exp.And(x => x.Time > queryInfo.DateStart);

            if (queryInfo.DateEnd != null)
                exp.And(x => x.Time < queryInfo.DateEnd);

            //exp.AndIF(
            //    !string.IsNullOrWhiteSpace(queryInfo.Query),
            //    x => x.WorkOderId.Contains(queryInfo.Query)
            //);

            //exp.AndIF(queryInfo.DateStart != null, x => x.Time > queryInfo.DateStart);

            //exp.AndIF(queryInfo.DateEnd != null, x => x.Time < queryInfo.DateEnd);

            //exp.AndIF(
            //    queryInfo.DateEnd != null && queryInfo.DateStart != null,
            //    x => (x.Time < queryInfo.DateEnd && x.Time > queryInfo.DateStart)
            //);

            //vue 分页仅仅 需要总数量 和 当前页. 而handycontrol 需要 总页数(用总数量算出来) 和当前页. 都不需要sqlsugar的 totalpage 总页数


            //var a = await helper
            //    .Db.Queryable<WorkOrderFeedback>()
            //    .Where(exp.ToExpression())
            //    .ToPageListAsync(queryInfo.Pagenum, queryInfo.Pagesize, total);

            //var aa = new MyApiResponse<List<WorkOrderFeedback>>(true, a);
            //aa.Total = total;
            //aa.Pagenum = queryInfo.Pagenum;
            //return aa;

            var resultList = await helper
                .Db.Queryable<WorkOrderFeedback>()
                .Where(exp.ToExpression())
                .ToPageListAsync(queryInfo.Pagenum, queryInfo.Pagesize, total);
            return new MyApiResponse<List<WorkOrderFeedback>>(true, resultList)
            {
                Total = total,
                Pagenum = queryInfo.Pagenum
            };
        }

        /// <summary>
        /// 单个删除
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public IActionResult DeleteWorkOderById(string id)
        {
            int count = this
                .helper.Db.Deleteable<WorkOrderFeedback>()
                .In(int.Parse(id))
                .ExecuteCommand();
            if (count > 0)
            {
                return Ok();
            }
            else
            {
                return StatusCode(204, "Failed");
            }
        }
    }
}
